import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * IPGuard加密
 */
public class EncryptIPGuard {

    static final RestTemplate restTemplate = new RestTemplate();

    static{
        // 创建绕过证书验证的SSLContext
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        try {
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
            }}, new SecureRandom());
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    }

    public static void main(String[] args) {

        String token = loginTest();
        System.out.println("token: " + token);



//        decryptTest(token, "C:\\APS\\plm-drawing\\2024-09\\Z185-0102-01-GX.DRW_sign_A.1.pdf");
    }

    public static String loginTest() {
        String str = "https://172.31.3.108/interface/wapi/login";
        Map<String, Object> params = new HashMap<>();
        params.put("Name", "FTP");
        params.put("Password", "Aa@123456");
        HashMap<String, String> hashMap = restTemplate.postForObject(str, params, HashMap.class);

        if(!hashMap.get("error").equals("0")){
            throw SyExceptionUtils.e(hashMap.get("desc"));
        }

        return hashMap.get("loginid");

    }

    public static void decryptTest(String loginId, String filePath) {
        String str = "https://172.31.3.108/interface/wapi/decryptFile";
        Map<String, Object> params = new HashMap<>();
        params.put("LoginID", loginId);
        params.put("File", filePath);
        HashMap<String, String> resMap = restTemplate.postForObject(str, params, HashMap.class);
        if(!resMap.get("error").equals("0")){
            throw SyExceptionUtils.e(resMap.get("desc"));
        }
        System.out.println("解密成功---" + filePath);


//        LoginID 是String 登录ID
//        File 是String 要解密的文件路径
//                字段类型描述
//        error String 错误代码，0表示成功，其他表示错误
//        desc String 错误描述
    }
}
